//
//  WJPDFContentViewController.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/22.
//

import UIKit
import PDFKit
import SnapKit

class WJPDFContentViewController: WJBaseViewViewController {
    
    // MARK: - Properties
    private var pdfDocument: PDFDocument?
    lazy var pdfView: PDFView = {
        let view = PDFView()
        view.autoScales = false
        view.displayMode = .singlePage
        view.displayDirection = .horizontal
        view.isInMarkupMode = true
        view.usePageViewController(true, withViewOptions: [UIPageViewController.OptionsKey.interPageSpacing: 20])
        boxProvider.pdfView = view
        view.pageOverlayViewProvider = boxProvider
        view.backgroundColor = .clear
        return view
    }()
    private var pdfFilePath: String?
    private var tabBarView = WJPDFTabBarView()
    
    var listModel: WJPDFListModel? = nil
    var boxProvider = WJPDFBoxProvider()
    
    // 缩略图容器
    lazy var thumbnailContainer: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.clear
        view.layer.cornerRadius = 8
        view.layer.masksToBounds = true
        return view
    }()

    lazy var thumbnailCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: 50, height: 70)
        layout.minimumLineSpacing = 8
        layout.minimumInteritemSpacing = 8
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(WJPDFThumbnailCell.self, forCellWithReuseIdentifier: "ThumbnailCell")
        return collectionView
    }()
    private var thumbnailData: [PDFThumbnailItem] = []
    
    private var drawSignatureTitle = "Your Drawn Signature"
    
    // MARK: - 分页缩放相关属性
    private var currentScale: CGFloat = 1.0
    private let minScale: CGFloat = 0.5
    private let maxScale: CGFloat = 3.0
    private var isZooming = false
    
    // MARK: - PDF 加载状态管理
    private var isPDFLoaded = false
    private var initialDisplayAttempted = false
    private var displayRetryCount = 0
    private let maxRetryCount = 3
    
    // MARK: - Data Models
    struct PDFThumbnailItem {
        let pageIndex: Int
        var thumbnailImage: UIImage?
        var isSelected: Bool = false
    }
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupConstraints()
        setNavigationItem()
        setupGestureRecognizers()
        
        if let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first,
           let path = listModel?.filePath {
            let fileURL = documentsURL.appendingPathComponent(path)
            self.pdfFilePath = fileURL.path
        }
        
        // 延迟加载PDF，确保视图完全布局
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            if let filePath = self.pdfFilePath {
                self.loadPDFFromPath(filePath)
            }
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 如果PDF已加载但显示有问题，重新尝试显示
        if isPDFLoaded && !initialDisplayAttempted {
            attemptToDisplayFirstPage()
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        pdfView.permanentlyHideAllIndicators()
        
        // 只有在PDF已加载且尚未成功显示时才尝试调整
        if isPDFLoaded && !initialDisplayAttempted && pdfView.bounds.width > 0 {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                self.attemptToDisplayFirstPage()
            }
        }
    }
    
    func setNavigationItem() {
        let leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "Icon_line_close"), style: .plain, target: self, action: #selector(clickLeftBarItemAction(_:)))
        self.navigationItem.leftBarButtonItem = leftBarButtonItem
        
        let rightButton = UIButton(type: .custom)
        rightButton.setTitle("Save", for: .normal)
        rightButton.backgroundColor = UIColor(hex: "#1F87F6")
        rightButton.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
        rightButton.titleLabel?.font = UIFont.montserratRegular(12)
        rightButton.layer.masksToBounds = true
        rightButton.layer.cornerRadius = 16
        rightButton.addTarget(self, action: #selector(saveButtonTapped(_:)), for: .touchUpInside)
        rightButton.frame = CGRect(x: 0, y: 0, width: 60, height: 32)
        let rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        self.navigationItem.rightBarButtonItem = rightBarButtonItem
    }
    
    @objc func clickLeftBarItemAction(_ item: UIBarButtonItem) {
        dismiss(animated: true)
    }
    
    @objc func saveButtonTapped(_ button: UIButton) {
        
        guard WJUserManager.shared.isVIP else {
            let vc = RemoteConfigValues.getCurrentPurchaseVC()
            let nav = WJNavigationController(rootViewController: vc)
            nav.modalPresentationStyle = .fullScreen
//            nav.modalTransitionStyle = .crossDissolve
            self.present(nav, animated: true)
            return
        }
        
        guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first,
              let path = listModel?.filePath  else { return }
        WJProgressHUD.showLoading()
        let fileURL = documentsURL.appendingPathComponent(path)
        let success = self.boxProvider.saveNewPDFToFile(at: fileURL)
        if success {
            if let model = self.listModel {
                model.signState = true
                model.createdDate = Date()
                let _ = try? model.update()
            }
            NotificationCenter.default.post(name: .pdfSignedNotification, object: nil)
        }
        WJProgressHUD.dismiss()
        self.dismiss(animated: true)
    }
    
    // MARK: - 分页缩放方法
    private func setupGestureRecognizers() {
        // 双击缩放
        let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:)))
        doubleTapGesture.numberOfTapsRequired = 2
        pdfView.addGestureRecognizer(doubleTapGesture)
        
        // 捏合缩放
        let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:)))
        pdfView.addGestureRecognizer(pinchGesture)
    }
    
    @objc private func handleDoubleTap(_ gesture: UITapGestureRecognizer) {
        if currentScale > 1.0 {
            // 重置缩放
            resetZoomAnimated()
        } else {
            // 放大到适合宽度
            safeZoomToFitWidth()
        }
    }
    
    @objc private func handlePinch(_ gesture: UIPinchGestureRecognizer) {
        switch gesture.state {
        case .began:
            isZooming = true
        case .changed:
            let scale = gesture.scale
            updateZoom(scale: scale)
            gesture.scale = 1.0
        case .ended, .cancelled:
            // 限制在最小和最大缩放比例之间
            currentScale = max(minScale, min(maxScale, currentScale))
            applyCurrentScale()
            isZooming = false
        default:
            break
        }
    }
    
    private func animateZoom(to scale: CGFloat) {
        isZooming = true
        UIView.animate(withDuration: 0.3, animations: {
            self.currentScale = scale
            self.applyCurrentScale()
        }) { _ in
            self.isZooming = false
        }
    }
    
    private func resetZoomAnimated() {
        animateZoom(to: 1.0)
    }
    
    private func updateZoom(scale: CGFloat) {
        // 防止 NaN 值
        guard scale.isFinite && !scale.isNaN else { return }
        
        currentScale *= scale
        currentScale = max(minScale, min(maxScale, currentScale))
        applyCurrentScale()
    }
    
    private func applyCurrentScale() {
        let scale = currentScale
        // 确保缩放值是有效的
        guard scale.isFinite && !scale.isNaN && scale > 0 else {
            currentScale = 1.0
            return
        }
        
        // 更新 PDFView 的缩放变换
        if let pageViewController = findPageViewController() {
            for case let scrollView as UIScrollView in pageViewController.view.subviews {
                scrollView.zoomScale = scale
                scrollView.minimumZoomScale = minScale
                scrollView.maximumZoomScale = maxScale
            }
        }
        
        updateNavigationTitle()
    }
    
    // MARK: - 安全的缩放计算方法
    private func safeZoomToFitWidth() {
        guard let page = pdfView.currentPage else { return }
        
        let pageBounds = page.bounds(for: .mediaBox)
        
        // 验证页面边界是否有效
        guard !pageBounds.isEmpty && pageBounds.width > 0 && pageBounds.height > 0 else {
            print("Invalid page bounds: \(pageBounds)")
            applySafeDefaultZoom()
            return
        }
        
        let viewWidth = pdfView.bounds.width - 40
        
        // 验证视图宽度是否有效
        guard viewWidth > 0 else {
            print("Invalid view width: \(viewWidth)")
            applySafeDefaultZoom()
            return
        }
        
        let scale = viewWidth / pageBounds.width
        
        // 验证缩放值是否有效
        guard scale.isFinite && !scale.isNaN && scale > 0 else {
            print("Invalid scale calculated: \(scale)")
            applySafeDefaultZoom()
            return
        }
        
        currentScale = max(minScale, min(maxScale, scale))
        applyCurrentScale()
    }
    
    private func applySafeDefaultZoom() {
        // 应用安全的默认缩放
        currentScale = 1.0
        applyCurrentScale()
    }
    
    private func safeZoomToFitPage() {
        guard let page = pdfView.currentPage else { return }
        
        let pageBounds = page.bounds(for: .mediaBox)
        
        // 验证页面边界是否有效
        guard !pageBounds.isEmpty && pageBounds.width > 0 && pageBounds.height > 0 else {
            print("Invalid page bounds for fit page: \(pageBounds)")
            applySafeDefaultZoom()
            return
        }
        
        let viewSize = pdfView.bounds.insetBy(dx: 20, dy: 20).size
        
        // 验证视图尺寸是否有效
        guard viewSize.width > 0 && viewSize.height > 0 else {
            print("Invalid view size: \(viewSize)")
            applySafeDefaultZoom()
            return
        }
        
        let widthScale = viewSize.width / pageBounds.width
        let heightScale = viewSize.height / pageBounds.height
        
        // 验证缩放值是否有效
        guard widthScale.isFinite && !widthScale.isNaN && widthScale > 0,
              heightScale.isFinite && !heightScale.isNaN && heightScale > 0 else {
            print("Invalid scales calculated - width: \(widthScale), height: \(heightScale)")
            applySafeDefaultZoom()
            return
        }
        
        let scale = min(widthScale, heightScale)
        currentScale = max(minScale, min(maxScale, scale))
        applyCurrentScale()
    }
    
    private func findPageViewController() -> UIPageViewController? {
        // 查找 PDFView 中的 UIPageViewController
        for subview in pdfView.subviews {
            if let pageViewController = findViewController(of: UIPageViewController.self, in: subview) {
                return pageViewController
            }
        }
        return nil
    }
    
    private func findViewController<T: UIViewController>(of type: T.Type, in view: UIView) -> T? {
        var responder: UIResponder? = view
        while let r = responder {
            if let vc = r as? T {
                return vc
            }
            responder = r.next
        }
        return nil
    }
    
    // MARK: - PDF 显示问题修复
    private func attemptToDisplayFirstPage() {
        guard isPDFLoaded, let document = pdfDocument, document.pageCount > 0 else { return }
        
        displayRetryCount += 1
        print("Attempting to display first page, attempt: \(displayRetryCount)")
        
        // 检查当前页面是否有效
        if let currentPage = pdfView.currentPage {
            let pageBounds = currentPage.bounds(for: .mediaBox)
            if isValidPageBounds(pageBounds) {
                // 页面有效，应用缩放
                initialDisplayAttempted = true
                print("Page bounds valid: \(pageBounds)")
                applyInitialZoom()
                return
            } else {
                print("Invalid page bounds detected: \(pageBounds)")
            }
        } else {
            print("No current page found")
        }
        
        // 如果当前页面无效，强制跳转到第一页
        if let firstPage = document.page(at: 0) {
            print("Forcing navigation to first page")
            pdfView.go(to: firstPage)
            
            // 强制布局更新
            pdfView.layoutIfNeeded()
            pdfView.setNeedsDisplay()
            
            // 检查页面是否成功显示
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                self.checkPageDisplayStatus()
            }
        }
        
        // 如果重试次数过多，使用备用方案
        if displayRetryCount >= maxRetryCount {
            print("Max retry count reached, using alternative method")
            useAlternativeDisplayMethod()
        }
    }
    
    private func isValidPageBounds(_ bounds: CGRect) -> Bool {
        return !bounds.isEmpty &&
               bounds.width > 0 &&
               bounds.height > 0 &&
               bounds.width.isFinite &&
               bounds.height.isFinite &&
               !bounds.width.isNaN &&
               !bounds.height.isNaN
    }
    
    private func checkPageDisplayStatus() {
        guard let currentPage = pdfView.currentPage else {
            print("No current page in check")
            // 没有当前页面，再次尝试
            if displayRetryCount < maxRetryCount {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    self.attemptToDisplayFirstPage()
                }
            }
            return
        }
        
        let pageBounds = currentPage.bounds(for: .mediaBox)
        if isValidPageBounds(pageBounds) {
            // 页面成功显示
            initialDisplayAttempted = true
            print("Page successfully displayed with bounds: \(pageBounds)")
            applyInitialZoom()
        } else if displayRetryCount < maxRetryCount {
            // 页面边界无效，再次尝试
            print("Page bounds still invalid: \(pageBounds)")
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self.attemptToDisplayFirstPage()
            }
        } else {
            print("Failed to display page after all attempts")
        }
    }
    
    private func useAlternativeDisplayMethod() {
        // 备用方案：重新设置PDF文档
        guard let document = pdfDocument, let firstPage = document.page(at: 0) else { return }
        
        print("Using alternative display method")
        
        // 临时移除再重新添加文档
        pdfView.document = nil
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            self.pdfView.document = document
            self.pdfView.go(to: firstPage)
            
            // 强制缩放
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self.safeZoomToFitWidth()
                self.initialDisplayAttempted = true
            }
        }
    }
    
    private func applyInitialZoom() {
        guard initialDisplayAttempted else { return }
        
        // 延迟应用缩放，确保页面完全渲染
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            self.safeZoomToFitWidth()
        }
    }
    
    // MARK: - Public Methods
    func loadPDFFromPath(_ filePath: String) {
        self.pdfFilePath = filePath
        loadPDFDocument()
    }
    
    func loadPDFFromModel(_ model: WJPDFListModel) {
        guard let filePath = model.filePath else {
            WJProgressHUD.showError(with: "Failed")
            return
        }
        self.pdfFilePath = filePath
        loadPDFDocument()
        navigationItem.title = model.name ?? "PDF Documents"
    }
    
    // MARK: - Private Methods
    private func setupUI() {
        view.backgroundColor = UIColor(hex: "#F3F3F3")
        view.addSubview(pdfView)
        view.addSubview(thumbnailContainer)
        thumbnailContainer.addSubview(self.thumbnailCollectionView)
        tabBarView.buttonTappedHandler = { [weak self] index in
            guard let self = self else { return }
            switch index {
            case 0:
                pushToSignatureHistoryVC()
            case 1:
                pushToDrawSignVC(animated: true)
            case 2:
                pushToFontsListVC()
            default:
                break
            }
        }
        view.addSubview(tabBarView)
        setupNotifications()
    }
    
    private func setupConstraints() {
        pdfView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(thumbnailContainer.snp.top).offset(-10)
        }
        
        tabBarView.snp.makeConstraints { make in
            make.leading.bottom.trailing.equalToSuperview()
            make.height.equalTo(49 + safeAreaBottom)
        }
        
        thumbnailContainer.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(tabBarView.snp.top).offset(-20)
            make.height.equalTo(80)
        }
        
        thumbnailCollectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    private func setupNotifications() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(pdfViewPageChanged(_:)),
            name: .PDFViewPageChanged,
            object: pdfView
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(applicationDidBecomeActive),
            name: UIApplication.didBecomeActiveNotification,
            object: nil
        )
    }
    
    @objc private func applicationDidBecomeActive() {
        // 应用重新激活时重新调整缩放
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            self.applyCurrentScale()
        }
    }
    
    private func pushToDrawSignVC(animated: Bool) {
        let vc = WJPDFDrawSignViewController()
        vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: animated)
    }
    
    private func pushToSignatureHistoryVC() {
        let vc = WJSignatureHistoryViewController()
        vc.delegate = self
        self.present(vc, animated: true)
    }
    
    private func pushToFontsListVC() {
        let vc = WJSignatureFontsListViewController()
        vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    private func loadPDFDocument() {
        guard let filePath = pdfFilePath else {
            WJProgressHUD.showError(with: "Failed")
            return
        }
        
        let fileURL = URL(fileURLWithPath: filePath)
        
        guard FileManager.default.fileExists(atPath: filePath) else {
            WJProgressHUD.showError(with: "Failed")
            return
        }
        
        WJProgressHUD.showLoading()
        
        // 重置状态
        isPDFLoaded = false
        initialDisplayAttempted = false
        displayRetryCount = 0
        
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            guard let self = self else { return }
            
            if let pdfDoc = PDFDocument(url: fileURL) {
                DispatchQueue.main.async {
                    WJProgressHUD.dismiss()
                    self.pdfDocument = pdfDoc
                    self.pdfView.document = pdfDoc
                    self.isPDFLoaded = true
                    self.setupThumbnailData()
                    self.updateNavigationTitle()
                    
                    print("PDF document loaded with \(pdfDoc.pageCount) pages")
                    
                    // 延迟确保 PDF 视图已正确布局
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                        self.attemptToDisplayFirstPage()
                    }
                }
            } else {
                DispatchQueue.main.async {
                    WJProgressHUD.dismiss()
                    WJProgressHUD.showError(with: "Failed to load PDF document")
                }
            }
        }
    }
    
    // MARK: - 缩略图数据设置
    private func setupThumbnailData() {
        guard let document = pdfDocument else { return }
        
        thumbnailData.removeAll()
        let pageCount = document.pageCount
        
        // 初始化数据
        for i in 0..<pageCount {
            let item = PDFThumbnailItem(pageIndex: i, thumbnailImage: nil)
            thumbnailData.append(item)
        }
        
        thumbnailCollectionView.reloadData()
        
        // 异步加载缩略图
        loadAllThumbnails()
    }
    
    private func loadAllThumbnails() {
        guard let document = pdfDocument else { return }
        
        DispatchQueue.global(qos: .background).async {
            for i in 0..<document.pageCount {
                if let page = document.page(at: i) {
                    let thumbnailSize = CGSize(width: 100, height: 100)
                    let thumbnail = page.thumbnail(of: thumbnailSize, for: .mediaBox)
                    
                    DispatchQueue.main.async {
                        if i < self.thumbnailData.count {
                            self.thumbnailData[i].thumbnailImage = thumbnail
                            
                            // 只更新可见的cell
                            if let cell = self.thumbnailCollectionView.cellForItem(at: IndexPath(item: i, section: 0)) as? WJPDFThumbnailCell {
                                cell.configure(with: self.thumbnailData[i])
                            }
                        }
                    }
                }
            }
        }
    }
    
    // MARK: - 缩略图滚动和定位
    private func scrollToThumbnail(at pageIndex: Int, animated: Bool = true) {
        guard pageIndex >= 0 && pageIndex < thumbnailData.count else { return }
        
        let indexPath = IndexPath(item: pageIndex, section: 0)
        thumbnailCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: animated)
    }
    
    private func updateThumbnailSelection(for pageIndex: Int) {
        // 更新所有缩略图的选中状态
        for i in 0..<thumbnailData.count {
            thumbnailData[i].isSelected = (i == pageIndex)
        }
        
        // 刷新可见的cell
        thumbnailCollectionView.visibleCells.forEach { cell in
            if let thumbnailCell = cell as? WJPDFThumbnailCell,
               let indexPath = thumbnailCollectionView.indexPath(for: cell) {
                thumbnailCell.configure(with: thumbnailData[indexPath.item])
            }
        }
        
        // 滚动到选中的缩略图
        scrollToThumbnail(at: pageIndex)
    }
    
    // MARK: - 页面跳转
    private func goToPage(_ pageIndex: Int) {
        guard let document = pdfView.document,
              pageIndex >= 0 && pageIndex < document.pageCount,
              let page = document.page(at: pageIndex) else { return }
        
        pdfView.go(to: page)
    }
    
    // MARK: - 更新界面状态
    private func updateNavigationTitle() {
        guard let document = pdfView.document,
              let currentPage = pdfView.currentPage else {
            navigationItem.title = "Loading..."
            return
        }
        
        let pageCount = document.pageCount
        let pageIndex = document.index(for: currentPage)
        
        if pageIndex >= 0 && pageIndex < pageCount {
            navigationItem.title = "Pages \(pageIndex + 1) of \(pageCount)"
            updateThumbnailSelection(for: pageIndex)
        } else {
            navigationItem.title = "Pages 1 of \(pageCount)"
        }
    }
    
    @objc private func pdfViewPageChanged(_ notification: Notification) {
        updateNavigationTitle()
        
        // 页面切换时保持当前的缩放比例
        if !isZooming {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                self.applyCurrentScale()
            }
        }
    }
    
    // MARK: - 签名相关方法
    private func createSignatureViewBox(signatureImage: UIImage, title: String, isHistory: Bool) {
        guard let currentPage = pdfView.currentPage else {
            WJProgressHUD.showError(with: "No current page")
            return
        }
        
        let newBox = WJPDFSignatureBoxView()
        newBox.signatureImage = signatureImage
        let y = self.pdfView.frame.maxY - CGFloat(Int.random(in: 30...80))
        let x = kScreenWidth - CGFloat(Int.random(in: 30...80))
        newBox.frame = CGRect(origin: CGPoint(x: x, y: y),
                              size: signatureBoxSize)
        self.boxProvider.referencePDFDocument = self.pdfDocument
        self.boxProvider.addBoxViewToPage(currentPage, boxView: newBox)
        
        if !isHistory {
            let historyModel = WJSignatureHistoryModel()
            historyModel.name = title
            historyModel.imageData = signatureImage.pngData()
            historyModel.createdDate = Date()
            historyModel.signType = 0
            let _ = try? historyModel.save()
        }
    }

    // MARK: - 内存管理
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - UICollectionViewDataSource
extension WJPDFContentViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return thumbnailData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ThumbnailCell", for: indexPath) as? WJPDFThumbnailCell else {
            return UICollectionViewCell()
        }
        
        let item = thumbnailData[indexPath.item]
        cell.configure(with: item)
        return cell
    }
}

// MARK: - UICollectionViewDelegate
extension WJPDFContentViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let pageIndex = indexPath.item
        goToPage(pageIndex)
        
        // 点击动画
        if let cell = collectionView.cellForItem(at: indexPath) as? WJPDFThumbnailCell {
            cell.animateSelection()
        }
    }
}

// MARK: - UICollectionViewDelegateFlowLayout
extension WJPDFContentViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 72, height: 72)
    }
}

// MARK: - WJPDFDrawSignViewControllerDelegate
extension WJPDFContentViewController: WJPDFDrawSignViewControllerDelegate {
    func didCreatePdfSign(_ controller: WJPDFDrawSignViewController, signatureImage: UIImage) {
        // 创建编辑框
        createSignatureViewBox(signatureImage: signatureImage,
                               title: drawSignatureTitle,
                               isHistory: false)
    }
}

extension WJPDFContentViewController: WJSignatureHistoryViewControllerDelegate {
    func useHistorySignature(controller: WJSignatureHistoryViewController, historyModel: WJSignatureHistoryModel) {
        if let imageData = historyModel.imageData,
        let image = UIImage(data: imageData) {
            createSignatureViewBox(signatureImage: image,
                                   title: historyModel.name ?? "",
                                   isHistory: true)
        }
    }
    
    func addNewSignature(controller: WJSignatureHistoryViewController) {
        pushToDrawSignVC(animated: true)
    }
}

extension WJPDFContentViewController: WJSignatureFontsListViewControllerDelegate {
    func useFontSignature(_ controller: WJSignatureFontsListViewController, signatureImage: UIImage, title: String) {
        createSignatureViewBox(signatureImage: signatureImage,
                               title: title,
                               isHistory: false)
    }
}
